import http from './request'
import previewImage from './image-viewer'
export * from './date'
export * from './prop'
export { http, previewImage }

const _toString = Object.prototype.toString

export function isRegExp(v) {
  return _toString.call(v) === '[object RegExp]'
}

export function isObject(v) {
  return v !== null && typeof v === 'object'
}

/**
 * 是否是原生Object对象
 * @param {any} obj
 */
export function isPlainObject(obj) {
  return _toString.call(obj) === '[object Object]'
}

/**
 * 是否是空、
 * @param {*} v
 */
export function isEmpty(v) {
  return v === undefined || v === '' || v === null
}

// 常见 MIME 类型列表 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
export const mimeType = {
  /* 扩展名: MIME 类型 */
  '.doc': 'application/msword',
  '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  '.pdf': 'application/pdf',
  '.ppt': 'application/vnd.ms-powerpoint',
  '.xls': 'application/vnd.ms-excel',
  '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}

/**
 * blob 数据保存为文件
 * @param {*} blobData blob数据
 * @param {string} fileName 保存文件名、在mac上，文件名必须要写后缀，要不然下载会有问题、在window上可以忽略
 */
export function blobSaveFile(blobData, fileName) {
  // const contentType = mimeType[extension]
  // if (contentType === undefined) {
  //   console.warn(`没有找到${extension}类型的文件`)
  // }
  fileName = decodeURI(fileName)

  const blob = new Blob([blobData] /* , { type: contentType } */)

  if ('msSaveOrOpenBlob' in window.navigator) {
    // ie使用的下载方式
    return window.navigator.msSaveOrOpenBlob(blob, fileName)
  }

  const objectUrl = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = objectUrl
  // 注意、在mac上，文件名必须要写后缀，要不然下载会有问题、在window上可以忽略
  a.download = fileName

  // 下面这个写法兼容火狐
  a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
  window.URL.revokeObjectURL(blob)
}

/**
 * 项目上传文件配置信息
 * 使用函数、为了保证headers变化
 * @type {{moduleName: {moduleName: string}, url: string}}
 */
export const uploadOptionsFn = function() {
  return {
    url: '/ent/file/uploadFile',
    headers: {
      AppId: sessionStorage.getItem('AppId'),
      Authorization: sessionStorage.getItem('Authorization')
    }
  }
}
